/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package framesettingsgui;

import ch.ubique.inieditor.IniEditor;
import framesettingsgui.Ausrueckordnung.fahrzeuge;
import framesettingsgui.elements.Label;
import framesettingsgui.elements.StatusLabel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JToggleButton;



/**
 *
 * @author rbs
 */
public class Frame{

    public String[] fahrzeugbez = {
        "ELW",
        "VRW",
        "LF16",
        "DL",
        "TLF",
        "W50",
        "RW",
        "GW"};

    public String[] schleifenbez = {
        "Gr. Gruppe",
        "Kl. Gruppe",
        "Drehleiter",
        "Rüstwagen",
        "Türnotöff.",
        "Wehrleitung",
    };

    public String[] e_typ_names = {
        "BR BRAND_1",
        "BR BRAND_2",
        "BR BRAND_3",
        "BR FAHRZEUG",
        "BR FELD", //TODO
        "BR BMA",
        "---wache Besetzen---",//TODO
        "---DL---", //TODO DL ->Über schleife
        "---DL_LICHTENSTEIN---", //DL_LICHTENSTEIN -> über Textauswertung
        "HILFE TH_1",
        "HILFE TH_2",
        "HILFE TH_3",
        "HILFE TÜR",
        "HILFE PERSON",
        "HILFE ABC",
        "HILFE WASSER"
    };
    
    //Der Frame selbst:
    private JFrame frame;
    //Die enthaltenen Elemente:
    private framesettingsgui.elements.Label e_typ;
    private Label e_txt;
    private framesettingsgui.elements.Label e_ort;
    private framesettingsgui.elements.Label e_nr;
    private framesettingsgui.elements.Label e_typ_name;
    private framesettingsgui.elements.Label e_txt_name;
    private framesettingsgui.elements.Label e_ort_name;
    private framesettingsgui.elements.Label e_nr_name;
    private framesettingsgui.elements.Label big_label;

    private framesettingsgui.elements.CountDownLabel countdown;

    private  framesettingsgui.elements.Label e_art;
    private  framesettingsgui.elements.Label[] schleifen = new Label[6];

    private JLabel status_bg;

    private StatusLabel[] status = new StatusLabel[8];

    private JButton end;
    private JButton debugbut;
    private JToggleButton snap_en;
    private int[] fahrzeugStatus = {0,0,0,0,0,0,0,0};

    private String eTyp = "Einsatz";

    private boolean[] schleifen_stat = new boolean[7];

    private Logger logger;

    private ComponentMover cm;
    private ComponentMover cm2;


    Frame()
    {
        logger = Logger.getLogger(Main.class.toString());
        logger.log(Level.INFO, "Frame wird initialisiert");
        frame = new JFrame("FW Display");
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setSize(Toolkit.getDefaultToolkit().getScreenSize());
        frame.setUndecorated(true);
        frame.getContentPane().setLayout(null);
        

        e_typ_name = new Label(this);
        e_typ = new Label(this);
        e_ort_name = new Label(this);
        e_ort = new Label(this);
        e_txt_name = new Label("E-Art:", this);
        e_txt = new Label(this);
        e_nr = new Label(this);
        status_bg = new Label(this);
        e_art = new Label(this);

        snap_en = new JToggleButton("Gitter an/aus");
        snap_en.addActionListener( new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (snap_en.isSelected())
                {
                    cm.setSnapSize(new Dimension(20, 20));
                    cm2.setSnapSize(new Dimension(20,20));

                }
                else
                {
                    cm.setSnapSize(new Dimension(1,1));
                    cm2.setSnapSize(new Dimension(1,1));
                }
            }
        });
        snap_en.setBounds(40, this.getHeigth() - 60, 100, 40);
        frame.add(snap_en);

        cm = new ComponentMover();
        cm.registerComponent(e_nr, e_art, e_typ, e_ort, e_txt, status_bg);
        cm.setSnapSize(new Dimension(1, 1));
        cm.setOnlyHorizontal();

        cm2 = new ComponentMover();
        cm2.setSnapSize(new Dimension(1,1));



        for(int i = 0; i < 8; i++)
        {
            status[i] = new StatusLabel(this);
            cm2.registerComponent(status[i]);
        }

        for(int i = 0; i < 6; i++)
        {
            schleifen[i] = new Label(this);
            cm2.registerComponent(schleifen[i]);
        }
        end = new JButton("Ende");
        debugbut = new JButton("DEBUG: ELW Status 3");
    }
    public int getWidth()
    {
        return frame.getWidth();
    }

    public int getHeigth()
    {
        return frame.getHeight();
    }

    //Returns one percent of the height:
    public int getPercHeight()
    {
        return frame.getHeight()/100;
    }

    public void setParams()
    {

    }

    public void showBigLabel(String text)
    {
        logger.log(Level.FINE, "Zeige ABBRUCH-FRAME");
        big_label = new Label("<html><p align=center>" + text, this);
        frame.add(big_label);
        big_label.setLocation(0, 0);
        big_label.setSize(getWidth(), getHeigth());
        big_label.setOpaque(true);
        big_label.setBackground(Color.green);
        big_label.setAlignment(Label.CENTER);
        big_label.setFont(new Font("serif", Font.BOLD, 120));
    }

    public void SetIniSettings()
    {
        logger.log(Level.FINE, "Lade Einstellungen von ini");
        e_typ.readSettings("settings.ini", "e-typ");
        e_typ.setLocation(0, getPercHeight() * 12);
        e_typ.setHorizontalAlignment(JLabel.CENTER);
        e_typ.setBorder(Color.LIGHT_GRAY, 1);
        
        e_ort.readSettings("settings.ini", "e-ort");
        e_ort.setLocation(0, getPercHeight() * 25);
        e_ort.setHorizontalAlignment(JLabel.CENTER);
        e_ort.setBorder(Color.LIGHT_GRAY, 1);

        e_txt.readSettings("settings.ini", "e-txt");
        e_txt.setLocation(0, getPercHeight() * 55);
        e_txt.setHorizontalAlignment(JLabel.CENTER);
        e_txt.setBorder(Color.LIGHT_GRAY, 1);

        e_nr.readSettings("settings.ini", "enr");
        e_nr.setLocation(0, getHeigth() - 20);
        e_nr.setHorizontalAlignment(JLabel.LEFT);
        e_nr.setOpaque(false);

        e_art.setLocation(0, 0);
        e_art.setSize(getWidth(), 30);
        e_art.setText(eTyp);
        e_art.setHorizontalAlignment(JLabel.CENTER);
        e_art.setBackground(new Color(100, 170, 80));
        e_art.setForeground(Color.WHITE);
        e_art.setFont(new Font("Arial", Font.BOLD, 18));
        e_art.setBorder(Color.LIGHT_GRAY, 1);

        logger.log(Level.FINE, "Lade status- und schleifen-Einstellungen");
        for(int i = 0; i < 8; i++)
        {
            status[i].setText(fahrzeugbez[i]);
            status[i].setLocation((getWidth() / 8) * i , getPercHeight()*90);
            status[i].SetWidth((int)(getWidth()/8));
            status[i].readSettings("settings.ini", "Status");
            status[i].setHorizontalAlignment(JLabel.CENTER);
        }
        
        for(int i = 0; i < 6; i++)
        {
            schleifen[i].setSize(getWidth()/6, 30);
            schleifen[i].setText(schleifenbez[i]);
            schleifen[i].setLocation((getWidth()/6)*i, 30);
            schleifen[i].setHorizontalAlignment(JLabel.CENTER);
            if(schleifen_stat[i])
            {
                schleifen[i].setBackground(new Color(100, 170, 80));
                schleifen[i].setForeground(Color.WHITE);
                schleifen[i].setFont(new Font("Arial", Font.BOLD, 18));
            }
            else
            {
                schleifen[i].setBackground(Color.darkGray);
                schleifen[i].setForeground(Color.gray);
            }

            schleifen[i].setOpaque(true);
        }

 }

    public void SetTexts(String type, String ort, String art, int nr)
    {
        e_typ.setText(type);
 
        e_ort.setText("<html><p align=center>" + ort);
 
        e_txt.setText("<html><p align=center>" + art);

        e_nr.setText("ENR: " + nr);
    }

    public void drawButtons(boolean debug)
    {
        logger.log(Level.FINE, "Zeichne Buttons");
        ActionListener aktion = new ActionListener() {
           public void actionPerformed(ActionEvent e){
                try {
                    update();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
                }
                System.exit(0);
            }
        };
                
        end.addActionListener(aktion);
        end.setSize(100, 30);
        end.setLocation(getWidth() - 120, getHeigth() - 50);
        end.setForeground(Color.blue);
        
        
        ActionListener debugaktion = new ActionListener() {
                public void actionPerformed(ActionEvent e){
                        SetStatusColor(0, Color.black, Color.green);
                        debugbut.setForeground(Color.green);
                }
        };
        
        debugbut.addActionListener(debugaktion);
        debugbut.setSize(160, 30);
        debugbut.setLocation(getWidth() - 340, getHeigth() - 50);
        debugbut.setForeground(Color.red);

    }

    private void update() throws IOException, InterruptedException
    {
        frame.setVisible(false);
        IniEditor reader = new IniEditor();
        reader.load("settings.ini");
        if (reader.get("updates", "mode").equals("after")) {
            Process proc = Runtime.getRuntime().exec("java -jar Updater.jar auto");
            proc.waitFor();
            System.exit(0);
        }
    }
    /**
     *
     * @param n_e_ort_x X-Pos von E-ORT-Beschriftung
     * @param n_e_ort_y Y-Pos von E-ORT-Beschriftung
     * @param e_ort_x   X-Pos von E-ORT
     * @param e_ort_y   Y-Pos von E-ORT
     * @param e_art_x   X-Pos von E-ART
     * @param e_art_y   Y-Pos von E-ART
     * @param e_nr_x    X-Pos von E-NR
     * @param e_nr_y    Y-Pos von E-NR
     * @param end_x     X-Pos von Button
     * @param end_y     Y-Pos von Button
     */
    public void SetPositions(int n_e_ort_x, int n_e_ort_y, int e_ort_x, 
            int e_ort_y, int e_art_x, int e_art_y, int e_nr_x,  int e_nr_y,
            int end_x, int end_y)
    {
        e_ort_name.setLocation(n_e_ort_x, getPercHeight() * n_e_ort_y);
        e_ort.setLocation(e_ort_x, getPercHeight() * e_ort_y);
        e_txt.setLocation(e_art_x, getPercHeight() * e_art_y);
        e_nr.setLocation(e_nr_x, getPercHeight() * e_nr_y);
        end.setLocation(end_x, end_y);
    }

    public void draw()
    {
        //Einsatzort-name:
       // frame.add(e_typ_name);
        e_typ_name.setOpaque(true);
        frame.add(e_typ);
        e_typ.setOpaque(true);
        //frame.add(e_ort_name);
        e_ort_name.setOpaque(true);
        //frame.add(e_txt_name);
        e_txt_name.setOpaque(true);
        frame.add(e_ort);
        e_ort.setOpaque(true);
        frame.add(e_txt);
        e_txt.setOpaque(true);
        frame.add(e_nr);
        e_nr.setOpaque(true);
        frame.add(e_art);
        e_art.setOpaque(true);

        frame.add(end);
        end.setOpaque(true);
        

        for (int i = 0; i < 8; i++)
        {
            frame.add(status[i]);
            status[i].setOpaque(true);
        }

        for (int i = 0; i < 6; i++)
        {
            frame.add(schleifen[i]);
            //schleifen[i].setOpaque(true);
        }


        ActionListener aktion = new ActionListener() {
                        public void actionPerformed(ActionEvent e){
                                System.exit(0);
                        }
        };


       
    }

    public void SetStatusColor(int car, Color fg, Color bg)
    {
        status[car].setForeground(fg);
        status[car].setBackground(bg);
    }

    public void SetStatusBorder(int car, boolean activ)
    {
        if (activ)
            status[car].setBorder(Color.black, 3);
        else
            status[car].setBorder(Color.black, 3);
    }

    public void SetStatusColors(String type, String ort)
    {
        int e_typ_num = -1;

        if (ort.contains("LICHTENSTEIN"))
        {
            e_typ_num = 8; //DL Lichtenstein
            if(type.contains("BRAND"))
                e_typ_num = 7;
        }
        else
        {
            for (int i = 0; i < e_typ_names.length; i++)
            {
                if (type.contains(e_typ_names[i]))
                {
                    e_typ_num = i;
                    break;
                }
            }
        }
        Ausrueckordnung ordnung = new Ausrueckordnung();
        
        fahrzeuge[] PrimFahrzeuge = null;
        fahrzeuge[] SecFahrzeuge = null;
        if (e_typ_num > 0)
        {
            PrimFahrzeuge = ordnung.getPrimFahrzeuge(e_typ_num);
            SecFahrzeuge = ordnung.getSecFahrzeuge(e_typ_num);

            for (int i=0; i < fahrzeugbez.length; i++)
                status[i].SetStatusInactive();

            for (int i=0; i < PrimFahrzeuge.length; i++)
            {
                for (int j= 0; j < 8; j ++)
                    if (PrimFahrzeuge[i] == fahrzeuge.values()[j])
                    {
                        status[j].SetStatus2();
                    }

            }
        }
    }

    public void SetExitMsg(String msg)
    {
        e_nr.setText(e_nr.getText() + "       " + msg);
    }

    public void SetBgColor(String e_typ)
    {
        IniEditor imp = new IniEditor("settings.ini");

        try {
            imp.load("settings.ini");
        }
        catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Fehler beim Lesen der Datei. Bitte die settings.ini neu herunterladen.");
            System.exit(-2);
        }

        if (e_typ.contains("BRAND") || e_typ.contains("BR"))
            frame.getContentPane().setBackground(Color.decode(imp.get("bgcolors", "brand")));
        else
            frame.getContentPane().setBackground(Color.decode(imp.get("bgcolors", "th")));

    }

    public void SetRICs(String input)
    {
        if (input.charAt(6) == 'A')
            eTyp = "Einsatz A";
        else if(input.charAt(6) == 'B')
            eTyp = "Einsatz B";
        else //=='X'
            eTyp = "Einsatz";
        
        for(int i = 0; i < 6; i++)
        {
            if(input.charAt(i) == '0')
                schleifen_stat[i] = false;
            else
                schleifen_stat[i] = true;

        }
    }

    public void addCountDown(String str, int time_ms)
    {
        countdown = new framesettingsgui.elements.CountDownLabel(this, str, time_ms);
        countdown.setLocation((int) (frame.getWidth() * 0.6), frame.getHeight() - 20);
        countdown.setSize(150, 100);
        countdown.setVisible(true);
        countdown.setOpaque(true);
        countdown.run();

        frame.add(countdown);
        
    }

    void SetTypPicture(String typ, String txt)
    {
        String picLoc = "";
        
        
        if (typ.contains("BR BRAND"))
            picLoc = "fwdisp/images/fire2-icon.png";
        if (typ.contains("BR BMA"))
            picLoc = "fwdisp/images/melder-icon.png";
        if (typ.contains("WASSER") || txt.contains("WASSER"))
            picLoc = "fwdisp/images/water-icon.png";
        if (typ.contains("HILFE TH"))
        {
            if(txt.contains("VKU"))
                picLoc = "fwdisp/images/vku-icon.png";
            else if(txt.contains("ÖLSPUR") || txt.contains("BM"))
                picLoc = "fwdisp/images/oil-icon.png";
            else if(txt.contains("BAUM") || txt.contains("AST"))
                picLoc = "fwdisp/images/chainsaw-icon.png";
        }
        if (typ.contains("HILFE TÜR"))
            picLoc = "fwdisp/images/schluessel-icon.png";
        if (typ.contains("HILFE PERSON"))
            picLoc = "fwdisp/images/people-icon.png";
        
        if (!picLoc.isEmpty()) //E-Typ erkannt
        {
            URL pic = ClassLoader.getSystemResource(picLoc);
            e_typ.SetLabelIcon(pic);
        }
    }

    void setVisible(boolean b) {
        frame.setVisible(b);
    }
}
